from iKBase import KBase
from django.conf import settings


class KBHelper():
    # 构造函数,初始化数据库连接
    def __init__(self,k_sql):
        self.k_sql = k_sql
        self.conn = None
        self.cur = None
        self.tpiclient = None
        self.sum_count = None

    def connectiondatabase(self):
        kbase_config = settings.DATABASES.get('kbase')
        try:
            # DSN形式参数
            self.conn = KBase.connect(host=kbase_config['host'], port=kbase_config['port'], user=kbase_config['user'], passwd=kbase_config['passwd'])
            self.tpiclient = KBase.TPIClient(self.conn)
        except:
            print('connectDatabase failed...')
            return False
        return True

    def closedatabase(self):
        # 如果数据打开，则关闭；否则没有操作
        if self.cur:
            self.cur.close()
            self.tpiclient.closeCon()
        if self.conn:
            self.conn.close()
        return True

    def select_fetchall(self):
        self.connectiondatabase()
        ret = self.tpiclient.openRecordSet(self.k_sql)
        if ret[0] >= 0:
            self.cur = ret[1]
            self.tpiclient.setCursor(self.cur)
            ret = self.tpiclient.moveFirst()

            # 返回记录集hSet中的记录个数
            count = self.tpiclient.getRecordSetCount()[0]
            result = self.cur.fetchall()
        else:
            result = list()

        self.closedatabase()
        return result

    def select_fetchone(self, cur_page=1, limit=0):
        self.connectiondatabase()
        ret = self.tpiclient.openRecordSet(self.k_sql)

        if ret[0] >= 0:
            self.cur = ret[1]
            self.tpiclient.setCursor(self.cur)
            # 返回记录集hSet中的记录个数
            self.sum_count = self.tpiclient.getRecordSetCount()[0]
            start = (cur_page-1)*limit + 1
            ret = self.tpiclient.move(start if start <= self.sum_count else 0)
            count = min(self.sum_count, limit) if limit else self.sum_count
            for i in range(count):
                yield self.cur.fetchone()
                if self.tpiclient.isEOF()[0]: break
        else:
            print(ret)
        self.closedatabase()

    def get_sum_count(self):
        if not self.sum_count:
            self.connectiondatabase()
            ret = self.tpiclient.openRecordSet(self.k_sql)
            if ret[0] >= 0:
                self.cur = ret[1]
                self.tpiclient.setCursor(self.cur)
                # 返回记录集hSet中的记录个数
                self.sum_count = self.tpiclient.getRecordSetCount()[0]
            self.closedatabase()
        return self.sum_count
